/**
 * 汽车销售管理系统 - UI组件增强
 * 
 * 提供表格、表单、分页等组件的交互增强功能
 */

(function() {
    'use strict';

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        initTables();
        initForms();
        initPagination();
        initSearchFilters();
        initModals();
        initTooltips();
        initResponsiveTables();
    });

    /**
     * 初始化表格功能
     */
    function initTables() {
        // 表格行悬停效果
        const tables = document.querySelectorAll('.table');
        tables.forEach(table => {
            const rows = table.querySelectorAll('tbody tr');
            rows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = 'rgba(66, 153, 225, 0.05)';
                });
                row.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '';
                });
            });
        });

        // 表格排序功能
        initTableSorting();
        
        // 表格选择功能
        initTableSelection();
    }

    /**
     * 初始化表格排序
     */
    function initTableSorting() {
        const sortableHeaders = document.querySelectorAll('.table th[data-sort]');
        sortableHeaders.forEach(header => {
            header.style.cursor = 'pointer';
            header.addEventListener('click', function() {
                const table = this.closest('table');
                const column = this.dataset.sort;
                const currentOrder = this.dataset.order || 'asc';
                const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
                
                // 更新排序指示器
                sortableHeaders.forEach(h => {
                    h.classList.remove('sort-asc', 'sort-desc');
                    delete h.dataset.order;
                });
                
                this.classList.add(`sort-${newOrder}`);
                this.dataset.order = newOrder;
                
                // 执行排序
                sortTable(table, column, newOrder);
            });
        });
    }

    /**
     * 表格排序实现
     */
    function sortTable(table, column, order) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        
        rows.sort((a, b) => {
            const aValue = a.querySelector(`[data-sort-value="${column}"]`)?.textContent.trim() || 
                          a.cells[getColumnIndex(table, column)]?.textContent.trim() || '';
            const bValue = b.querySelector(`[data-sort-value="${column}"]`)?.textContent.trim() || 
                          b.cells[getColumnIndex(table, column)]?.textContent.trim() || '';
            
            // 数字排序
            if (!isNaN(aValue) && !isNaN(bValue)) {
                return order === 'asc' ? aValue - bValue : bValue - aValue;
            }
            
            // 字符串排序
            return order === 'asc' ? 
                aValue.localeCompare(bValue, 'zh-CN') : 
                bValue.localeCompare(aValue, 'zh-CN');
        });
        
        // 重新插入排序后的行
        rows.forEach(row => tbody.appendChild(row));
    }

    /**
     * 获取列索引
     */
    function getColumnIndex(table, column) {
        const headers = table.querySelectorAll('th');
        for (let i = 0; i < headers.length; i++) {
            if (headers[i].dataset.sort === column) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 初始化表格选择功能
     */
    function initTableSelection() {
        const selectAllCheckboxes = document.querySelectorAll('.select-all');
        selectAllCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const table = this.closest('table');
                const rowCheckboxes = table.querySelectorAll('.select-row');
                rowCheckboxes.forEach(cb => {
                    cb.checked = this.checked;
                    toggleRowSelection(cb.closest('tr'), cb.checked);
                });
                updateBatchActions();
            });
        });

        const rowCheckboxes = document.querySelectorAll('.select-row');
        rowCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                toggleRowSelection(this.closest('tr'), this.checked);
                updateSelectAllState();
                updateBatchActions();
            });
        });
    }

    /**
     * 切换行选择状态
     */
    function toggleRowSelection(row, selected) {
        if (selected) {
            row.classList.add('table-row-selected');
        } else {
            row.classList.remove('table-row-selected');
        }
    }

    /**
     * 更新全选状态
     */
    function updateSelectAllState() {
        const selectAllCheckbox = document.querySelector('.select-all');
        if (selectAllCheckbox) {
            const rowCheckboxes = document.querySelectorAll('.select-row');
            const checkedCount = document.querySelectorAll('.select-row:checked').length;
            
            selectAllCheckbox.checked = checkedCount === rowCheckboxes.length;
            selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < rowCheckboxes.length;
        }
    }

    /**
     * 更新批量操作按钮状态
     */
    function updateBatchActions() {
        const selectedCount = document.querySelectorAll('.select-row:checked').length;
        const batchActions = document.querySelectorAll('.batch-action');
        
        batchActions.forEach(action => {
            action.disabled = selectedCount === 0;
            const countSpan = action.querySelector('.selected-count');
            if (countSpan) {
                countSpan.textContent = selectedCount;
            }
        });
    }

    /**
     * 初始化表单功能
     */
    function initForms() {
        // 表单验证增强
        const forms = document.querySelectorAll('form[novalidate]');
        forms.forEach(form => {
            form.addEventListener('submit', function(e) {
                if (!form.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // 滚动到第一个错误字段
                    const firstInvalid = form.querySelector('.form-control:invalid');
                    if (firstInvalid) {
                        firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        firstInvalid.focus();
                    }
                }
                form.classList.add('was-validated');
            });
        });

        // 实时验证
        const inputs = document.querySelectorAll('.form-control');
        inputs.forEach(input => {
            input.addEventListener('blur', function() {
                // 检查元素是否在form内
                if (this.form && this.form.classList.contains('was-validated')) {
                    this.checkValidity();
                }
            });
        });

        // 数字输入格式化
        initNumberInputs();
        
        // 日期输入限制
        initDateInputs();
    }

    /**
     * 初始化数字输入
     */
    function initNumberInputs() {
        const numberInputs = document.querySelectorAll('input[type="number"], .number-input');
        numberInputs.forEach(input => {
            input.addEventListener('input', function() {
                // 移除非数字字符（除了小数点）
                let value = this.value.replace(/[^0-9.]/g, '');
                
                // 确保只有一个小数点
                const parts = value.split('.');
                if (parts.length > 2) {
                    value = parts[0] + '.' + parts.slice(1).join('');
                }
                
                // 限制小数位数
                if (parts[1] && parts[1].length > 2) {
                    value = parts[0] + '.' + parts[1].substring(0, 2);
                }
                
                this.value = value;
            });
        });
    }

    /**
     * 初始化日期输入
     */
    function initDateInputs() {
        const dateInputs = document.querySelectorAll('input[type="date"]');
        const today = new Date().toISOString().split('T')[0];
        
        dateInputs.forEach(input => {
            // 设置默认的最大日期为今天
            if (!input.hasAttribute('max')) {
                input.setAttribute('max', today);
            }
        });
    }

    /**
     * 初始化分页功能
     */
    function initPagination() {
        const paginationLinks = document.querySelectorAll('.pagination .page-link');
        paginationLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                if (this.closest('.page-item').classList.contains('disabled')) {
                    e.preventDefault();
                    return false;
                }
                
                // 添加加载状态
                const originalText = this.innerHTML;
                this.innerHTML = '<div class="spinner-border spinner-border-sm"></div>';
                
                // 模拟加载延迟
                setTimeout(() => {
                    this.innerHTML = originalText;
                }, 500);
            });
        });
    }

    /**
     * 初始化搜索筛选功能
     */
    function initSearchFilters() {
        const searchInputs = document.querySelectorAll('.search-input');
        searchInputs.forEach(input => {
            let timeout;
            input.addEventListener('input', function() {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    // 实时搜索逻辑
                    performSearch(this.value);
                }, 300);
            });
        });

        // 筛选器重置
        const resetButtons = document.querySelectorAll('.filter-reset');
        resetButtons.forEach(button => {
            button.addEventListener('click', function() {
                const form = this.closest('form');
                if (form) {
                    form.reset();
                    form.submit();
                }
            });
        });
    }

    /**
     * 执行搜索
     */
    function performSearch(query) {
        // 这里可以实现AJAX搜索
        console.log('搜索:', query);
    }

    /**
     * 初始化模态框功能
     */
    function initModals() {
        const modalTriggers = document.querySelectorAll('[data-bs-toggle="modal"]');
        modalTriggers.forEach(trigger => {
            trigger.addEventListener('click', function() {
                const modalId = this.dataset.bsTarget;
                const modal = document.querySelector(modalId);
                if (modal) {
                    // 可以在这里添加模态框打开前的逻辑
                }
            });
        });
    }

    /**
     * 初始化工具提示
     */
    function initTooltips() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }

    /**
     * 初始化响应式表格
     */
    function initResponsiveTables() {
        const tables = document.querySelectorAll('.table-responsive-stack');
        tables.forEach(table => {
            const headers = table.querySelectorAll('th');
            const rows = table.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                cells.forEach((cell, index) => {
                    if (headers[index]) {
                        cell.setAttribute('data-label', headers[index].textContent.trim());
                    }
                });
            });
        });
    }

    // 暴露全局方法
    window.UIComponents = {
        sortTable,
        updateBatchActions,
        performSearch
    };

})();
